package com.seth.myapplication.surface;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.seth.myapplication.AcceptActivity;
import com.seth.myapplication.DataApp;
import com.seth.myapplication.R;
import com.seth.myapplication.bean.Rewords;
import com.seth.myapplication.bean.User;
import com.seth.myapplication.dialog.ImagePickerFragment;
import com.seth.myapplication.service.NetWorkService;

import java.io.File;
import java.util.ArrayList;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Seth on 2017/11/2.
 */

public class AcceptTask extends Fragment {
    public static final String TASK_COMPLETE_IMG = "task_back_img";
    public static final String TASK_COMPLETE_FILE = "task_back_file";
    public static final String TASK_COMPLETE_FLAG = "task_back_flag";

    private static final String EXTRA_TASK_POSITION = "00000000";
    private static final int REQUEST_IMG = 3;
    private Rewords reword;

    private Button acceptBtn;
    private CircleImageView usrNickImg;
    private CircleImageView geterNickImg;
    private TextView usrNameTxt;
    private TextView getNameTxt;
    private ImageView usrSex;
    private TextView taskContent;
    private ImageView taskimg1;
    private ImageView taskimg2;
    private ImageView taskimg3;
    private ImageView taskimg4;
    private TextView taskType;
    private TextView taskDeadTime;
    private TextView taskPrice;
    private TextView taskInsurance;

    private ImageBlock pic1;
    private ImageBlock pic2;
    private ImageBlock pic3;
    private ImageBlock pic4;

    private EditText completEdit;
    private RelativeLayout completeImgBlock;
    private RelativeLayout completeEditBolck;
    private RelativeLayout addImageBlocks;
    private ImageView addImageIcon;


    private Bitmap uploadBitmap;
    private File uploadFile;
    private ArrayList<ImageBlock> unsettedImg = new ArrayList<>();
    private ArrayList<ImageBlock> settedImg = new ArrayList<>();


    private DataApp dataApp;
    private User mUser;
    private AcceptBroadCast msgReceiver;
    private int flag;
    private int imgFlag;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_accept_task, container, false);
        dataApp = (DataApp) getActivity().getApplication();
        mUser = dataApp.getUser();

        Bundle bundle = getArguments();
        reword = (Rewords) bundle.getSerializable(EXTRA_TASK_POSITION);
        flag = bundle.getInt(AcceptActivity.EXTRA_FLAG,0);
        initView(view);


        initEvent();

        if(flag==0){
        }
        if(flag==3){
            initCompleteTaskView(view);
            initCompleteTaskEvent();
        }

        return view;
    }

    private void initCompleteTaskEvent() {
        completeImgBlock.setVisibility(View.VISIBLE);
        completeEditBolck.setVisibility(View.VISIBLE);
        initAddImageIcon(addImageIcon);

        addImageBlocks.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImagePickerFragment dialog =ImagePickerFragment.NewInstace(REQUEST_IMG,mUser.getPhoneNum());
                dialog.setTargetFragment(AcceptTask.this, REQUEST_IMG);
                dialog.show(getFragmentManager(), "选择图片来源");
            }
        });

        acceptBtn.setText("确认完成");
        acceptBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

    }

    private void initCompleteTaskView(View view) {
        completeImgBlock = (RelativeLayout) view.findViewById(R.id.task_complete_img_block);
        completeEditBolck = (RelativeLayout) view.findViewById(R.id.task_complete_edit_block);
        addImageBlocks = (RelativeLayout) view.findViewById(R.id.add_images_block);
        addImageIcon = (ImageView) view.findViewById(R.id.add_images);
        pic1 = new ImageBlock((ImageView) view.findViewById(R.id.task_img1),
                (ImageView) view.findViewById(R.id.task_img1_delete),
                (RelativeLayout) view.findViewById(R.id.block_img1),1);
        unsettedImg.add(pic1);
        pic2 = new ImageBlock((ImageView) view.findViewById(R.id.task_img2),
                (ImageView) view.findViewById(R.id.task_img2_delete),
                (RelativeLayout) view.findViewById(R.id.block_img2),2);
        unsettedImg.add(pic2);
        pic3 = new ImageBlock((ImageView) view.findViewById(R.id.task_img3),
                (ImageView) view.findViewById(R.id.task_img3_delete),
                (RelativeLayout) view.findViewById(R.id.block_img3),3);
        unsettedImg.add(pic3);
        pic4 = new ImageBlock((ImageView) view.findViewById(R.id.task_img4),
                (ImageView) view.findViewById(R.id.task_img4_delete),
                (RelativeLayout) view.findViewById(R.id.block_img4),4);
        unsettedImg.add(pic4);
        completEdit = (EditText) view.findViewById(R.id.task_complete_edit);
    }

    @Override
    public void onAttach(Context context) {

        //动态注册广播接收器
        msgReceiver = new AcceptBroadCast();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.seth.myapplication.service.ACCEPT.TASK");
        context.registerReceiver(msgReceiver, intentFilter);
        super.onAttach(context);
    }

    @Override
    public void onDestroy() {
        getActivity().unregisterReceiver(msgReceiver);
        super.onDestroy();
    }

    private void initEvent() {
        acceptBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mUser==null){
                    Toast.makeText(getContext(), "请先登录", Toast.LENGTH_SHORT).show();
                }else if(mUser.getUsrId() == reword.getUsrId()){
                    Toast.makeText(getContext(), "请不要认领您自己的悬赏", Toast.LENGTH_SHORT).show();
                }else{
                    new NetWorkService(getActivity()).AcceptTask(mUser.getUsrId(), reword.getRewordId());
                }
            }
        });
    }

    private void initView(View view) {
        geterNickImg = (CircleImageView) view.findViewById(R.id.accepted_usr);
        usrNickImg = (CircleImageView) view.findViewById(R.id.accept_usr_nick);
        getNameTxt = (TextView) view.findViewById(R.id.accepted_usr_name);
        usrNameTxt = (TextView) view.findViewById(R.id.accept_usr_name);

        usrSex = (ImageView) view.findViewById(R.id.accept_usr_sex);
        acceptBtn = (Button) view.findViewById(R.id.accept_btn);
        taskType = (TextView) view.findViewById(R.id.accept_task_type);
        taskimg1 = (ImageView) view.findViewById(R.id.get_task_img1);
        taskimg2 = (ImageView) view.findViewById(R.id.get_task_img2);
        taskimg3 = (ImageView) view.findViewById(R.id.get_task_img3);
        taskimg4 = (ImageView) view.findViewById(R.id.get_task_img4);
        taskContent = (TextView) view.findViewById(R.id.accept_task_content);
        taskDeadTime = (TextView) view.findViewById(R.id.accept_task_deadtime);
        taskPrice = (TextView) view.findViewById(R.id.accept_task_price);
        taskInsurance = (TextView) view.findViewById(R.id.accept_task_insurance);

        taskPrice.setText("￥"+reword.getPrice()+"");

        taskDeadTime.setText("截至日期："+reword.getTaskDeadTime());
        taskContent.setText(reword.getTaskContent());
        if(reword.isBuyInsurance()==1){
            taskInsurance.setVisibility(View.VISIBLE);
        }else {
            taskInsurance.setVisibility(View.INVISIBLE);
        }
        updategeter();
        if(reword.getTaskImg1Url()!=null){
            setTaskImg(taskimg1,reword.getTaskImg1Url());
            if(reword.getTaskImg2Url()!=null){
                setTaskImg(taskimg2,reword.getTaskImg2Url());
                if(reword.getTaskImg3Url()!=null){
                    setTaskImg(taskimg3,reword.getTaskImg3Url());
                    if(reword.getTaskImg4Url()!=null){
                        setTaskImg(taskimg4,reword.getTaskImg4Url());
                    }
                }
            }
        }
    }

    private void updategeter() {
        User geter = reword.getGeter();
        if(geter==null){
            geterNickImg.setVisibility(View.GONE);
            getNameTxt.setVisibility(View.GONE);
        }
    }

    private void setTaskImg(ImageView taskImg, File taskImgUrl) {
        taskImg.setVisibility(View.VISIBLE);
        String path = taskImgUrl.getPath();
        Bitmap bm = BitmapFactory.decodeFile(path);
        taskImg.setImageBitmap(bm);
    }


    private class AcceptBroadCast extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            String msg = intent.getStringExtra("result");
            Intent i = new Intent();
            if("success".equals(msg)){
                Toast.makeText(context, "成功接受悬赏，请在我的任务中查看", Toast.LENGTH_SHORT).show();
                i.putExtra("msg",msg);
                i.putExtra("reword",reword);
            }else{
                i.putExtra("msg",msg);
                Toast.makeText(context, "接受悬赏失败", Toast.LENGTH_SHORT).show();
            }
            getActivity().setResult(page3Fragment.ACCEPT_RERSULT,i);
        }
    }

    void initAddImageIcon(ImageView img) {
        ViewGroup.LayoutParams params =  img.getLayoutParams();
        params.height = 100;
        params.width = 100;
        img.setLayoutParams(params);
        img.setImageResource(R.drawable.ic_add_msg);
    }

    @Override
    public void onActivityResult(int resquestCode, int resultCode, Intent data) {
        Log.i("UploagImage", "设置图片返回结果");
        Log.i("UploagImage", "更新"+resquestCode);

        if(resquestCode == REQUEST_IMG){
            Log.i("UploagImage", "更新");
            uploadBitmap = data.getParcelableExtra(TASK_COMPLETE_IMG);
            uploadFile = (File) data.getSerializableExtra(TASK_COMPLETE_FILE);
            imgFlag =  data.getIntExtra(TASK_COMPLETE_FLAG,1);
            addUploadImage();
        }

    }

    private void addUploadImage() {
        ImageBlock temp = unsettedImg.remove(0);
        if(unsettedImg.isEmpty())
            addImageBlocks.setVisibility(View.GONE);
        temp.setUploadPIc(uploadBitmap);
        settedImg.add(temp);
    }

    class ImageBlock{
        ImageView uploadPIc;
        ImageView deletIcon;
        RelativeLayout block;
        Bitmap mBitmap;
        int id;
        public ImageBlock(ImageView uploadPIc, ImageView deletIcon, RelativeLayout block, int id) {
            this.uploadPIc = uploadPIc;
            this.deletIcon = deletIcon;
            this.block = block;
            this.id = id;

            deletIcon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.i("UploagImage", "bolck_size"+settedImg.size());
                    Log.i("UploagImage", "更新bolck"+settedImg.indexOf(this));
                    removeImag(settedImg.indexOf(ImageBlock.this));
                }
            });
        }
        void setUploadPIc(Bitmap bitmap){
            block.setVisibility(View.VISIBLE);
            deletIcon.setVisibility(View.VISIBLE);
            mBitmap = bitmap;
            uploadPIc.setImageBitmap(mBitmap);
        }

        void removeImag(int index){
            ImageBlock temp = settedImg.remove(index);
            temp.clearBlock();
            unsettedImg.add(0,temp);
            if(settedImg.size()==3){
                addImageBlocks.setVisibility(View.VISIBLE);
            }
        }
        void clearBlock(){
            block.setVisibility(View.GONE);
        }
        @Override
        public boolean equals(Object obj) {
            if (obj instanceof ImageBlock) {
                if (this.id == ((ImageBlock) obj).id) {
                    return true;
                }
                else {
                    return false;
                }
            }
            return false;
        }

        @Override
        public int hashCode() {
            return 10222;
        }
    }





}
